<template>
  <div class="guide-detail-page">
    <!-- 面包屑导航 -->
    <div class="container mx-auto px-4 py-4">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/tour-guide' }"
          >导游服务</el-breadcrumb-item
        >
        <el-breadcrumb-item>{{ guideDetail.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              导游详情
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              了解导游详细信息，选择最适合您的导游
            </p>
          </div>
          <el-button class="back-btn" @click="router.back()">
            <el-icon class="mr-1"><Back /></el-icon>
            返回上一页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧主要内容 -->
        <div class="lg:col-span-2">
          <!-- 导游基本信息 -->
          <div
            class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden mb-6"
          >
            <div class="p-6">
              <div class="flex items-center space-x-6">
                <el-avatar
                  :size="120"
                  :src="guideDetail.avatar"
                  class="border-4 border-gray-100 dark:border-gray-700 shadow-sm"
                />
                <div class="flex-1">
                  <h2
                    class="text-3xl font-bold text-gray-900 dark:text-white mb-2"
                  >
                    {{ guideDetail.name }}
                  </h2>
                  <div class="flex items-center space-x-4">
                    <div class="flex items-center">
                      <el-rate
                        v-model="guideDetail.rating"
                        disabled
                        show-score
                        class="!text-yellow-400"
                      />
                      <span class="ml-2 text-gray-500"
                        >{{ guideDetail.reviewCount }}条评价</span
                      >
                    </div>
                  </div>
                </div>
                <div class="text-right">
                  <div
                    class="text-3xl font-bold text-primary-600 dark:text-primary-400 mb-2"
                  >
                    ¥{{ guideDetail.price
                    }}<span class="text-lg font-normal">/天</span>
                  </div>
                  <el-button type="primary" size="large" @click="handleBook">
                    立即预约
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 导游介绍 -->
          <div
            class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden mb-6"
          >
            <div class="p-6">
              <h3
                class="text-xl font-bold text-gray-900 dark:text-white mb-6 flex items-center"
              >
                <el-icon class="mr-2 text-primary-500"><Document /></el-icon>
                导游介绍
              </h3>
              <div class="prose dark:prose-invert max-w-none">
                <div v-html="guideDetail.introduction"></div>
              </div>
            </div>
          </div>

          <!-- 擅长路线 -->
          <div
            class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden mb-6"
          >
            <div class="p-6">
              <h3
                class="text-xl font-bold text-gray-900 dark:text-white mb-6 flex items-center"
              >
                <el-icon class="mr-2 text-primary-500"><Van /></el-icon>
                擅长路线
              </h3>
              <div class="space-y-4">
                <div
                  v-for="route in guideDetail.routes"
                  :key="route.id"
                  class="route-card p-6 border border-gray-100 dark:border-gray-700 rounded-xl hover:shadow-lg transition-all duration-300"
                >
                  <div class="flex items-start justify-between">
                    <div class="flex-1">
                      <h4
                        class="text-lg font-bold text-gray-900 dark:text-white mb-2"
                      >
                        {{ route.name }}
                      </h4>
                      <p class="text-gray-600 dark:text-gray-400 text-sm mb-4">
                        {{ route.description }}
                      </p>
                      <div
                        class="flex items-center space-x-6 text-sm text-gray-500"
                      >
                        <span class="flex items-center">
                          <el-icon class="mr-2"><Timer /></el-icon>
                          {{ route.duration }}
                        </span>
                        <span class="flex items-center">
                          <el-icon class="mr-2"><Location /></el-icon>
                          {{ route.spots.length }}个景点
                        </span>
                      </div>
                    </div>
                    <el-button
                      type="primary"
                      plain
                      @click="showRouteDetail(route)"
                    >
                      查看详情
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 用户评价 -->
          <div
            class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden"
          >
            <div class="p-6">
              <div class="flex items-center justify-between mb-8">
                <h3
                  class="text-xl font-bold text-gray-900 dark:text-white flex items-center"
                >
                  <el-icon class="mr-2 text-primary-500"><ChatRound /></el-icon>
                  用户评价
                </h3>
                <div class="flex items-center space-x-4">
                  <div
                    class="text-4xl font-bold text-primary-600 dark:text-primary-400"
                  >
                    {{ guideDetail.rating }}
                  </div>
                  <div class="text-sm text-gray-500">
                    共{{ guideDetail.reviewCount }}条评价
                  </div>
                  <el-button type="primary" @click="showReviewDialog = true"
                    >写评价</el-button
                  >
                </div>
              </div>
              <div class="space-y-8">
                <div
                  v-for="review in guideDetail.reviews"
                  :key="review.id"
                  class="review-item"
                >
                  <div class="flex items-start space-x-4">
                    <el-avatar :size="48" :src="review.user.avatar" />
                    <div class="flex-1">
                      <div class="flex items-center justify-between mb-2">
                        <div>
                          <span class="font-bold text-gray-900 dark:text-white">
                            {{ review.user.name }}
                          </span>
                          <span class="text-gray-500 text-sm ml-2">
                            {{ review.date }}
                          </span>
                        </div>
                        <el-rate v-model="review.rating" disabled />
                      </div>
                      <p
                        class="text-gray-600 dark:text-gray-400 mb-4 text-base leading-relaxed"
                      >
                        {{ review.content }}
                      </p>
                      <div
                        class="flex items-center text-sm text-gray-500 bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3"
                      >
                        <span class="flex items-center">
                          <el-icon class="mr-1"><Calendar /></el-icon>
                          游玩时间：{{ review.tourDate }}
                        </span>
                        <span class="mx-4">|</span>
                        <span class="flex items-center">
                          <el-icon class="mr-1"><User /></el-icon>
                          {{ review.groupSize }}人出行
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧信息 -->
        <div class="lg:col-span-1">
          <div class="sticky top-4 space-y-6">
            <!-- 预约日历 -->
            <div
              class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden"
            >
              <div class="p-6">
                <h3
                  class="text-xl font-bold text-gray-900 dark:text-white mb-6 flex items-center"
                >
                  <el-icon class="mr-2 text-primary-500"><Calendar /></el-icon>
                  预约日历
                </h3>
                <div class="booking-calendar space-y-6">
                  <el-date-picker
                    v-model="selectedDate"
                    type="date"
                    :disabled-date="disabledDate"
                    class="!w-full"
                    :shortcuts="[
                      {
                        text: '今天',
                        value: new Date(),
                      },
                      {
                        text: '明天',
                        value: (() => {
                          const date = new Date();
                          date.setTime(date.getTime() + 3600 * 1000 * 24);
                          return date;
                        })(),
                      },
                      {
                        text: '一周后',
                        value: (() => {
                          const date = new Date();
                          date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
                          return date;
                        })(),
                      },
                    ]"
                  />

                  <!-- 推荐行程选择 -->
                  <div class="recommended-routes">
                    <div class="flex items-center justify-between mb-3">
                      <div
                        class="text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        推荐行程
                      </div>
                      <el-tag type="success" size="small" effect="plain"
                        >{{ guideDetail.routes.length }}条路线</el-tag
                      >
                    </div>
                    <div class="space-y-2">
                      <el-radio-group
                        v-model="bookingForm.routeId"
                        class="w-full flex flex-col gap-2"
                      >
                        <el-radio
                          v-for="route in guideDetail.routes"
                          :key="route.id"
                          :label="route.id"
                          class="!w-full !h-auto !m-0 !p-0"
                        >
                          <div
                            class="route-option p-3 border border-gray-100 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 w-full"
                          >
                            <div class="flex flex-col">
                              <span
                                class="font-medium text-gray-900 dark:text-white"
                                >{{ route.name }}</span
                              >
                              <div
                                class="flex items-center text-xs text-gray-500 mt-1 space-x-2"
                              >
                                <span class="flex items-center">
                                  <el-icon class="mr-1"><Timer /></el-icon>
                                  {{ route.duration }}
                                </span>
                                <span class="text-gray-300 dark:text-gray-600"
                                  >|</span
                                >
                                <span class="flex items-center">
                                  <el-icon class="mr-1"><Location /></el-icon>
                                  {{ route.spots.length }}个景点
                                </span>
                              </div>
                            </div>
                          </div>
                        </el-radio>
                      </el-radio-group>
                    </div>
                  </div>

                  <!-- 预约提示 -->
                  <div
                    class="booking-tips bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4"
                  >
                    <h4
                      class="text-sm font-medium text-gray-900 dark:text-white mb-2"
                    >
                      预约说明
                    </h4>
                    <ul
                      class="text-xs text-gray-500 dark:text-gray-400 space-y-1"
                    >
                      <li class="flex items-center">
                        <el-icon class="mr-1"><InfoFilled /></el-icon>
                        提前至少1天预约
                      </li>
                      <li class="flex items-center">
                        <el-icon class="mr-1"><Timer /></el-icon>
                        服务时长: 8小时/天
                      </li>
                      <li class="flex items-center">
                        <el-icon class="mr-1"><User /></el-icon>
                        每个时段限定人数: 6人
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>

            <!-- 服务保障 -->
            <div
              class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden"
            >
              <div class="p-6">
                <h3
                  class="text-xl font-bold text-gray-900 dark:text-white mb-6 flex items-center"
                >
                  <el-icon class="mr-2 text-primary-500"
                    ><CircleCheck
                  /></el-icon>
                  服务保障
                </h3>
                <div class="space-y-6">
                  <div
                    class="flex items-start space-x-4 p-4 rounded-lg bg-primary-50 dark:bg-primary-900/20"
                  >
                    <el-icon class="text-xl text-primary-500 mt-1"
                      ><CircleCheck
                    /></el-icon>
                    <div>
                      <h4 class="font-bold text-gray-900 dark:text-white mb-1">
                        平台认证
                      </h4>
                      <p class="text-sm text-gray-600 dark:text-gray-400">
                        导游信息已通过平台实名认证
                      </p>
                    </div>
                  </div>
                  <div
                    class="flex items-start space-x-4 p-4 rounded-lg bg-green-50 dark:bg-green-900/20"
                  >
                    <el-icon class="text-xl text-green-500 mt-1"
                      ><Document
                    /></el-icon>
                    <div>
                      <h4 class="font-bold text-gray-900 dark:text-white mb-1">
                        保险保障
                      </h4>
                      <p class="text-sm text-gray-600 dark:text-gray-400">
                        全程提供旅行意外保险
                      </p>
                    </div>
                  </div>
                  <div
                    class="flex items-start space-x-4 p-4 rounded-lg bg-blue-50 dark:bg-blue-900/20"
                  >
                    <el-icon class="text-xl text-blue-500 mt-1"
                      ><Service
                    /></el-icon>
                    <div>
                      <h4 class="font-bold text-gray-900 dark:text-white mb-1">
                        客服支持
                      </h4>
                      <p class="text-sm text-gray-600 dark:text-gray-400">
                        7*24小时专属客服服务
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预约弹窗 -->
    <el-dialog
      v-model="showBookingDialog"
      title="预约导游"
      width="500px"
      destroy-on-close
      class="booking-dialog"
    >
      <div class="space-y-6">
        <div
          class="booking-info bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6"
        >
          <div class="flex items-center space-x-4 mb-4">
            <el-avatar :size="48" :src="guideDetail.avatar" />
            <div>
              <h4 class="font-bold text-gray-900 dark:text-white">
                {{ guideDetail.name }}
              </h4>
              <div class="text-sm text-gray-500">
                {{ guideDetail.certifications[0] }}
              </div>
            </div>
          </div>
          <div class="flex justify-between text-sm text-gray-500">
            <span>服务价格</span>
            <span class="text-lg font-bold text-primary-600"
              >¥{{ guideDetail.price }}/天</span
            >
          </div>
        </div>
        <div class="form-group">
          <div class="label mb-2">选择日期</div>
          <el-date-picker
            v-model="bookingForm.date"
            type="date"
            placeholder="请选择预约日期"
            :disabled-date="disabledDate"
            class="!w-full"
          />
        </div>
        <div class="form-group">
          <div class="label mb-2">服务时间</div>
          <div class="grid grid-cols-3 gap-2">
            <el-button
              v-for="time in availableTimes"
              :key="time"
              :type="bookingForm.startTime === time ? 'primary' : ''"
              @click="bookingForm.startTime = time"
            >
              {{ time }}
            </el-button>
          </div>
        </div>
        <div class="form-group">
          <div class="label mb-2">游客人数</div>
          <el-input-number
            v-model="bookingForm.people"
            :min="1"
            :max="20"
            class="!w-full"
          />
        </div>
        <div class="form-group">
          <div class="label mb-2">联系方式</div>
          <el-input v-model="bookingForm.phone" placeholder="请输入手机号码" />
        </div>
        <div class="form-group">
          <div class="label mb-2">备注信息</div>
          <el-input
            v-model="bookingForm.remarks"
            type="textarea"
            rows="3"
            placeholder="请输入特殊需求或其他备注信息"
          />
        </div>
      </div>
      <template #footer>
        <div class="flex items-center justify-between">
          <div class="total-price">
            <span class="text-gray-500">费用：</span>
            <span class="text-2xl text-primary-600 font-bold">
              ¥{{ guideDetail.price }}
            </span>
          </div>
          <div class="space-x-2">
            <el-button @click="showBookingDialog = false">取消</el-button>
            <el-button
              type="primary"
              :disabled="!isValidBooking"
              @click="handleConfirmBooking"
            >
              确认预约
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 路线详情弹窗 -->
    <el-dialog
      v-if="selectedRoute"
      v-model="showRouteDialog"
      :title="selectedRoute.name"
      width="600px"
      class="route-dialog"
    >
      <div class="space-y-6">
        <div class="route-info bg-gray-50 dark:bg-gray-800 rounded-lg p-6">
          <p class="text-gray-600 dark:text-gray-400 mb-4">
            {{ selectedRoute.description }}
          </p>
          <div class="flex items-center space-x-6">
            <div class="flex items-center text-gray-500">
              <el-icon class="mr-2 text-primary-500"><Timer /></el-icon>
              <span>行程时长：{{ selectedRoute.duration }}</span>
            </div>
            <div class="flex items-center text-gray-500">
              <el-icon class="mr-2 text-primary-500"><Van /></el-icon>
              <span>交通方式：{{ selectedRoute.transportation }}</span>
            </div>
          </div>
        </div>
        <div class="route-spots">
          <h4 class="font-bold text-lg mb-6">行程安排</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(spot, index) in selectedRoute.spots"
              :key="index"
              :timestamp="spot.time"
              placement="top"
              :type="index === 0 ? 'primary' : ''"
            >
              <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm">
                <h5 class="font-bold mb-2">{{ spot.name }}</h5>
                <p class="text-sm text-gray-600 dark:text-gray-400">
                  {{ spot.description }}
                </p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 评价弹窗 -->
    <el-dialog
      v-model="showReviewDialog"
      title="写评价"
      width="500px"
      destroy-on-close
    >
      <div class="space-y-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <el-avatar :size="48" :src="guideDetail.avatar" />
            <div>
              <h4 class="font-bold text-gray-900 dark:text-white">
                {{ guideDetail.name }}
              </h4>
              <div class="text-sm text-gray-500">
                {{ guideDetail.certifications[0] }}
              </div>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="label mb-2">服务评分</div>
          <el-rate
            v-model="reviewForm.rating"
            :texts="['很差', '较差', '一般', '不错', '很好']"
            show-text
          />
        </div>
        <div class="form-group">
          <div class="label mb-2">评价内容</div>
          <el-input
            v-model="reviewForm.content"
            type="textarea"
            rows="4"
            placeholder="请分享您的游玩体验..."
          />
        </div>
        <div class="form-group">
          <div class="label mb-2">游玩时间</div>
          <el-date-picker
            v-model="reviewForm.tourDate"
            type="date"
            placeholder="请选择游玩时间"
            class="!w-full"
          />
        </div>
        <div class="form-group">
          <div class="label mb-2">出行人数</div>
          <el-input-number
            v-model="reviewForm.groupSize"
            :min="1"
            :max="20"
            class="!w-full"
          />
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showReviewDialog = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!isValidReview"
            @click="handleSubmitReview"
          >
            提交评价
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Back,
  Timer,
  ChatRound,
  Medal,
  Location,
  Calendar,
  User,
  Shield,
  Document,
  Service,
  Van,
  InfoFilled,
  CircleCheck,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import service from "@/api/axios"; // 导入axios服务

const router = useRouter();
const route = useRoute();

// 导游详细信息
const guideDetail = ref({
  id: 1,
  name: "李明",
  avatar: "/images/guides/guide1.jpg",
  rating: 4.8,
  reviewCount: 256,
  price: 380,
  experience: 5,
  servedCount: 1280,
  goodReviewRate: 98,
  languages: ["中文", "英语"],
  certifications: ["高级导游证"],
  location: "贵港市",
  introduction: `
    <p>您好，我是李明，从事导游工作5年，是一名持证高级导游。</p>
    <p>我对贵港的历史文化有深入研究，特别擅长为游客讲解历史故事和民俗文化。在这些年的工作中，我积累了丰富的带团经验，获得了众多游客的好评。</p>
    <p>作为导游，我的职责不仅是带领大家游览景点，更重要的是让每位游客能够深入了解贵港的文化内涵，感受这座城市的独特魅力。</p>
    <p>我会根据不同游客的需求，定制个性化的游览路线，让您的贵港之旅既轻松愉快，又收获满满。</p>
  `,
  routes: [
    {
      id: 1,
      name: "贵港文化精华一日游",
      description: "深度体验贵港历史文化，探访人文景点",
      duration: "8小时",
      transportation: "步行+公交",
      spots: [
        {
          time: "09:00-10:30",
          name: "贵港博物馆",
          description: "了解贵港历史文化，参观珍贵文物展览",
        },
        {
          time: "10:45-12:00",
          name: "古城墙遗址",
          description: "探访古城遗迹，感受历史沧桑",
        },
        {
          time: "13:30-15:00",
          name: "文庙",
          description: "参观贵港最完整的古建筑群",
        },
        {
          time: "15:30-17:00",
          name: "江滨公园",
          description: "欣赏江景，了解水运文化",
        },
      ],
    },
    {
      id: 2,
      name: "贵港美食文化之旅",
      description: "品尝地道美食，了解饮食文化",
      duration: "6小时",
      transportation: "步行",
      spots: [
        {
          time: "09:00-10:30",
          name: "贵港美食街",
          description: "品尝特色小吃，了解美食文化",
        },
        {
          time: "11:00-12:30",
          name: "传统市场",
          description: "参观本地市场，了解食材文化",
        },
        {
          time: "14:00-15:30",
          name: "老字号店铺",
          description: "走访百年老店，品尝传统美食",
        },
      ],
    },
  ],
  reviews: [
    {
      id: 1,
      user: {
        name: "张先生",
        avatar: "/images/avatars/user1.jpg",
      },
      rating: 5,
      content:
        "导游非常专业，对贵港的历史文化了解很深，讲解生动有趣。全程服务态度很好，是一次很棒的旅游体验！",
      date: "2024-03-15",
      tourDate: "2024-03-10",
      groupSize: 4,
    },
    {
      id: 2,
      user: {
        name: "李女士",
        avatar: "/images/avatars/user2.jpg",
      },
      rating: 5,
      content:
        "李导游很贴心，不仅带我们参观了景点，还推荐了很多好吃的地方。讲解很专业，让我们学到了很多贵港的历史知识。",
      date: "2024-03-12",
      tourDate: "2024-03-08",
      groupSize: 2,
    },
  ],
});

// 预约相关
const showBookingDialog = ref(false);
const bookingForm = reactive({
  date: "",
  startTime: "",
  people: 1,
  phone: "",
  remarks: "",
  routeId: null,
});

// 路线详情
const showRouteDialog = ref(false);
const selectedRoute = ref(null);

// 评价相关
const showReviewDialog = ref(false);
const reviewForm = reactive({
  rating: 5,
  content: "",
  tourDate: "",
  groupSize: 1,
});

// 日历相关
const selectedDate = ref(new Date());

// 禁用的日期（今天之前的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};

// 预约表单是否有效
const isValidBooking = computed(() => {
  return (
    bookingForm.date &&
    bookingForm.startTime &&
    bookingForm.people > 0 &&
    bookingForm.phone
  );
});

// 评价表单是否有效
const isValidReview = computed(() => {
  return (
    reviewForm.rating > 0 &&
    reviewForm.content.trim() !== "" &&
    reviewForm.tourDate &&
    reviewForm.groupSize > 0
  );
});

// 获取导游详情信息
const fetchGuideDetail = async (guideId) => {
  try {
    // 调用公共API获取导游详情
    const response = await service.get(`/public/tour-guides/${guideId}`);
    
    if (response && response.data) {
      guideDetail.value = response.data;
    }
    // 如果没有返回数据，则保留测试数据
  } catch (error) {
    console.error("获取导游详情失败:", error);
    // 失败时使用测试数据
    ElMessage.error("获取导游详情失败，显示默认数据");
  }
};

// 获取导游预约时间槽
const fetchAvailableTimeSlots = async (guideId, date) => {
  if (!guideId || !date) return;
  
  try {
    const formattedDate = dayjs(date).format("YYYY-MM-DD");
    // 调用公共API获取可用时间槽
    const response = await service.get(`/public/tour-guides/${guideId}/time-slots`, {
      params: { date: formattedDate }
    });
    
    if (response && response.data) {
      // 根据返回数据更新可用时间槽
      // 这里假设后端返回的是可用时间段的数组
      return response.data;
    }
    // 如果没有返回数据，使用默认测试数据
    return availableTimes;
  } catch (error) {
    console.error("获取可用时间槽失败:", error);
    // 失败时使用测试数据
    return availableTimes;
  }
};

// 处理预约
const handleBook = () => {
  // 检查用户是否登录
  const token = localStorage.getItem("token");
  if (!token) {
    ElMessage.warning("请先登录后再预约");
    router.push({
      path: "/login",
      query: { redirect: `/tour-guide/${guideDetail.value.id}` },
    });
    return;
  }
  
  // 已登录则显示预约对话框
  showBookingDialog.value = true;
};

// 确认预约
const handleConfirmBooking = async () => {
  try {
    // 准备预约数据
    const bookingData = {
      guideId: guideDetail.value.id,
      guideName: guideDetail.value.name,
      guideAvatar: guideDetail.value.avatar,
      date: dayjs(bookingForm.date).format("YYYY-MM-DD"),
      startTime: bookingForm.startTime,
      people: bookingForm.people,
      phone: bookingForm.phone,
      remarks: bookingForm.remarks,
      routeId: bookingForm.routeId,
      routeName:
        guideDetail.value.routes.find((r) => r.id === bookingForm.routeId)
          ?.name || "",
      price: guideDetail.value.price,
      type: "guide", // 设置订单类型为guide
    };

    // 调用需要认证的API创建预约
    await service.post('/tour-guide-bookings', bookingData);

    // 提示成功并关闭对话框
    ElMessage.success("预约成功！");
    showBookingDialog.value = false;

    // 将预约数据编码为URL参数，以便传递给确认页面
    const encodedData = encodeURIComponent(JSON.stringify(bookingData));

    // 跳转到订单确认页面，并传递预约数据
    router.push({
      name: "OrderConfirm",
      query: {
        type: "guide",
        data: encodedData,
      },
    });
  } catch (error) {
    console.error("预约失败:", error);
    ElMessage.error("预约失败，请重试");
  }
};

// 显示路线详情
const showRouteDetail = (route) => {
  selectedRoute.value = route;
  showRouteDialog.value = true;
};

// 提交评价
const handleSubmitReview = async () => {
  try {
    // 检查用户是否登录
    const token = localStorage.getItem("token");
    if (!token) {
      ElMessage.warning("请先登录后再评价");
      router.push({
        path: "/login",
        query: { redirect: `/tour-guide/${guideDetail.value.id}` },
      });
      return;
    }
    
    // 准备评价数据
    const reviewData = {
      guideId: guideDetail.value.id,
      rating: reviewForm.rating,
      content: reviewForm.content,
      tourDate: dayjs(reviewForm.tourDate).format("YYYY-MM-DD"),
      groupSize: reviewForm.groupSize
    };
    
    // 调用需要认证的API提交评价
    const response = await service.post('/tour-guide-reviews', reviewData);
    
    if (response) {
      // 如果提交成功，刷新评价列表
      ElMessage.success("评价提交成功");
      showReviewDialog.value = false;
      
      // 重新获取导游详情，包括更新的评价
      fetchGuideDetail(guideDetail.value.id);
    } else {
      // 如果没有返回数据，模拟前端处理
      const newReview = {
        id: Date.now(),
        user: {
          name: "游客",
          avatar: "/images/avatars/default.jpg",
        },
        rating: reviewForm.rating,
        content: reviewForm.content,
        date: dayjs().format("YYYY-MM-DD"),
        tourDate: dayjs(reviewForm.tourDate).format("YYYY-MM-DD"),
        groupSize: reviewForm.groupSize,
      };

      guideDetail.value.reviews.unshift(newReview);
      guideDetail.value.reviewCount++;

      // 重新计算平均评分
      const totalRating = guideDetail.value.reviews.reduce(
        (sum, review) => sum + review.rating,
        0,
      );
      guideDetail.value.rating = (
        totalRating / guideDetail.value.reviews.length
      ).toFixed(1);

      ElMessage.success("评价提交成功");
      showReviewDialog.value = false;
    }
  } catch (error) {
    console.error("评价提交失败:", error);
    ElMessage.error("评价提交失败，请重试");
  }
};

// 可预约时段数据
const availableTimes = [
  "08:00",
  "09:00",
  "10:00",
  "11:00",
  "13:00",
  "14:00",
  "15:00",
  "16:00",
];

// 可预约时段数量
const availableSlots = computed(() => {
  return availableTimes.filter((time) => isTimeSlotAvailable(time)).length;
});

// 检查时间段是否可预约
const isTimeSlotAvailable = (time) => {
  // TODO: 实现实际的时间段可用性检查逻辑
  return Math.random() > 0.3; // 示例：随机返回是否可用
};

// 选择时间段
const selectTimeSlot = (time) => {
  if (isTimeSlotAvailable(time)) {
    bookingForm.startTime = time;
  }
};

// 页面加载时获取数据
onMounted(async () => {
  const guideId = route.params.id;
  if (guideId) {
    await fetchGuideDetail(guideId);
  } else {
    ElMessage.error("导游ID不存在");
    router.push('/tour-guide');
  }
});
</script>

<style lang="scss" scoped>
.guide-detail-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  :deep(.el-breadcrumb__item) {
    .el-breadcrumb__inner {
      color: theme("colors.gray.500");
      font-weight: normal;

      &.is-link {
        color: theme("colors.gray.500");

        &:hover {
          color: theme("colors.primary.500");
        }
      }
    }

    &:last-child {
      .el-breadcrumb__inner {
        color: theme("colors.gray.900");
        font-weight: 500;

        .dark & {
          color: theme("colors.white");
        }
      }
    }
  }

  .prose {
    @apply text-gray-600 dark:text-gray-300;

    p {
      @apply mb-4;
    }
  }

  .route-card {
    @apply bg-white dark:bg-gray-800;

    &:hover {
      @apply bg-gray-50 dark:bg-gray-700/50;
    }
  }

  .review-item {
    @apply border-b border-gray-100 dark:border-gray-700 pb-6 last:border-b-0 last:pb-0;
  }

  :deep(.el-rate) {
    .el-rate__icon {
      &.el-icon {
        @apply text-yellow-400 dark:text-yellow-500;
      }
    }
  }

  .booking-calendar {
    :deep(.el-date-picker) {
      width: 100%;
    }

    .recommended-routes {
      .el-radio-group {
        width: 100%;
      }

      :deep(.el-radio) {
        margin: 0;
        padding: 0;
        width: 100%;
        height: auto;

        .el-radio__input {
          position: absolute;
          left: 1rem;
          top: 50%;
          transform: translateY(-50%);
        }

        .el-radio__label {
          padding: 0;
          width: 100%;
        }

        .route-option {
          padding-left: 2.5rem;
          transition: all 0.3s ease;
        }

        &.is-checked {
          .route-option {
            @apply bg-primary-50 border-primary-200;

            .dark & {
              @apply bg-primary-900/20 border-primary-700;
            }
          }
        }
      }
    }

    .booking-tips {
      li {
        @apply flex items-center text-gray-500 dark:text-gray-400;

        .el-icon {
          @apply text-primary-500 dark:text-primary-400 mr-2;
        }
      }
    }
  }

  .label {
    @apply text-sm font-medium text-gray-700 dark:text-gray-300;
  }
}
</style>
